package cn.asiontang.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;

import java.io.File;
import java.security.MessageDigest;
import java.util.Locale;

public final class Utils
{
    private static int versionCode = -1;

    private static String versionName;

    private static String IMEICode;

    private static String IMSICode;

    private static String PhoneNumber;

    private static Boolean isRoot;

    private static final String TAG = Utils.class.getSimpleName();

    /**
     * 检查存储卡是否插入
     */
    public static final boolean checkIsHasSdcard()
    {
        final String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * MD5 加密
     */
    public static final String computeMd5(final String str)
    {
        MessageDigest messageDigest = null;

        try
        {
            messageDigest = MessageDigest.getInstance("MD5");

            messageDigest.reset();

            messageDigest.update(str.getBytes("UTF-8"));
        } catch (final Exception e)
        {
        }

        final byte[] byteArray = messageDigest.digest();

        final StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++)
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));

        return md5StrBuff.toString().toUpperCase(Locale.ENGLISH);
    }

    public static final int dip2px(final Context context, final float dpValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 计算sdcard上的剩余空间
     *
     * @return 返回还剩余多少MB。假如没有SD卡，则返回""
     */
    public static final String getFreeSpaceOnSd(final Context context)
    {
        if (!checkIsHasSdcard())
            return "";

        final StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        @SuppressWarnings("deprecation")
        final long blockSize = stat.getBlockSize();
        @SuppressWarnings("deprecation")
        final long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(context, availableBlocks * blockSize);
    }

    public static final String getIMEI(final Context context)
    {
        if (IMEICode == null)
        {
            final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            // 获取手机IMEI码
            IMEICode = TextUtils.valueOfNoNull(tm.getDeviceId());
            // 获取手机IMSI码
            IMSICode = TextUtils.valueOfNoNull(tm.getSubscriberId());
            // 获取手机号码
            PhoneNumber = TextUtils.valueOfNoNull(tm.getLine1Number());
        }
        return IMEICode;
    }

    public static final String getIMSI(final Context context)
    {
        if (IMSICode == null)
            getIMEI(context);
        return IMSICode;
    }

    /**
     * 获取手机型号
     */
    public static final String getPhoneModel()
    {
        return android.os.Build.MODEL;
    }

    public static final String getPhoneNumber(final Context context)
    {
        if (PhoneNumber == null)
            getIMEI(context);
        return PhoneNumber;
    }

    /**
     * @return Android的android.os.Build.VERSION.SDK_INT更加准确定义系统的版本。<br/>
     * 而android.os.Build.VERSION.RELEASE，则可能会有一些自定义显示文本如：4.4.R2,所以不采用<br/>
     */
    public static final String getPhoneSystemVersion()
    {
        return String.valueOf(android.os.Build.VERSION.SDK_INT);
    }

    public static final int getVersionCode(final Context context)
    {
        try
        {
            if (versionCode == -1)
            {
                // 获取packagemanager的实例
                final PackageManager packageManager = context.getPackageManager();
                // getPackageName()是你当前类的包名，0代表是获取版本信息
                final PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);

                versionCode = packInfo.versionCode;
                versionName = packInfo.versionName;
            }
            return versionCode;
        } catch (final NameNotFoundException e)
        {
            //吃掉异常
            return -1;
        }
    }

    public static final String getVersionName(final Context context)
    {
        if (versionName == null)
            getVersionCode(context);
        return versionName;
    }

    /**
     * 判断是否root
     */
    public static final boolean isRoot()
    {
        if (isRoot != null)
            return isRoot;
        try
        {
            if (new File("/system/bin/su").exists())
                isRoot = true;
            else if (new File("/system/xbin/su").exists())
                isRoot = true;
            else
                isRoot = false;
        } catch (final Exception e)
        {
            isRoot = false;
        }
        return isRoot;
    }

    public static final double obj2double(final Object text, final double defaultValue)
    {
        try
        {
            if (text == null)
                return defaultValue;
            if (text instanceof Double)
                return (Double) text;
            final String value = String.valueOf(text);
            if (TextUtils.isEmptyOrOnlyWhiteSpace(value))
                return defaultValue;
            return Double.parseDouble(value);
        } catch (final NumberFormatException ex)
        {
            return defaultValue;
        }
    }

    public static final float obj2float(final Object text, final float defaultValue)
    {
        try
        {
            if (text == null)
                return defaultValue;
            if (text instanceof Float)
                return (Float) text;
            final String value = String.valueOf(text);
            if (TextUtils.isEmptyOrOnlyWhiteSpace(value))
                return defaultValue;
            return Float.parseFloat(value);
        } catch (final NumberFormatException ex)
        {
            return defaultValue;
        }
    }

    public static final int obj2int(final Object text, final int defaultValue)
    {
        try
        {
            if (text == null)
                return defaultValue;
            if (text instanceof Integer)
                return (Integer) text;
            final String value = String.valueOf(text);
            if (TextUtils.isEmptyOrOnlyWhiteSpace(value))
                return defaultValue;
            //当字符串包含小数点时，默认使用Double转换，然后强制转换为int
            if (value.contains("."))
                return (int) Double.parseDouble(value);
            return Integer.parseInt(value);
        } catch (final NumberFormatException ex)
        {
            return defaultValue;
        }
    }

    public static final long obj2long(final Object text, final long defaultValue)
    {
        try
        {
            if (text == null)
                return defaultValue;
            if (text instanceof Long)
                return (Long) text;
            final String value = String.valueOf(text);
            if (TextUtils.isEmptyOrOnlyWhiteSpace(value))
                return defaultValue;
            return Long.parseLong(value);
        } catch (final NumberFormatException ex)
        {
            return defaultValue;
        }
    }
}
